﻿using Microsoft.EntityFrameworkCore;
using OpenIddict.Abstractions;

namespace IdentityApi.Data
{
    public class SeedData : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;

        public SeedData(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using var scope = _serviceProvider.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            await db.Database.MigrateAsync();
            //var strategy = db.Database.CreateExecutionStrategy();
            //await strategy.ExecuteAsync(async () =>
            //{
            //    // Run migration in a transaction to avoid partial migration if it fails.
            //    await db.Database.MigrateAsync();
            //});

            var applicationManager = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();

            // 检查是否存在指定的 client_id
            if (await applicationManager.FindByClientIdAsync("client_id1", cancellationToken) is null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId = "client_id1",
                    ClientSecret = "client_secret", // 根据需求设置密钥
                    DisplayName = "示例客户端应用",
                    Permissions =
                {
                    OpenIddictConstants.Permissions.Endpoints.Token,
                    OpenIddictConstants.Permissions.GrantTypes.Password,           // 允许密码模式
                    OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                    OpenIddictConstants.Permissions.Prefixes.Scope + "api",          // 允许访问的 API 作用域
                    // 添加offline_access作用域
                    OpenIddictConstants.Permissions.Prefixes.Scope + OpenIddictConstants.Scopes.OfflineAccess,
                }
                };

                await applicationManager.CreateAsync(descriptor, cancellationToken);
            }
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }

}
